package kmp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 给定两个字符串s和 p，找到s中所有p的异位词的子串，返回这些子串的起始索引。不考虑答案输出的顺序。
 *
 * 异位词 指由相同字母重排列形成的字符串（包括相同的字符串）。
 *
 */
public class leetCode438_findAnagrams {
    public List<Integer> findAnagrams(String s, String p) {
        if(s == null || p == null) return null;
        List<Integer> result = new ArrayList<>();

        HashMap<Character,Integer> need = new HashMap<>();
        HashMap<Character,Integer> window = new HashMap<>();

        int left = 0;
        int right = 0;
        int valid = 0;
        for (char c : p.toCharArray()) {
            need.put(c,need.getOrDefault(c,0) + 1);
        }

        while (right < s.length()){
            Character b = s.charAt(right);
            right++;
            if(need.containsKey(b)){
                window.put(b,window.getOrDefault(b,0) + 1);
                if(window.get(b).equals(need.get(b))){
                    valid++;
                }
            }
            while (right - left >= p.length()){
                if(valid == need.size()){
                    result.add(left);
                }
                Character c = s.charAt(left);
                left++;
                if(need.containsKey(c)){
                    if(window.containsKey(c)) {
                        if (window.get(c).equals(need.get(c))) {
                            valid--;
                        }
                    }
                    window.put(c, window.get(c) - 1);
                }
            }


        }
        return result;

    }
}
